from django import forms
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError


class LoginForm(forms.Form):
    """
    普通表单类，用户登录表单，不直接操纵数据库
    """
    username = forms.CharField(
        max_length=11,
        label='请输入您的手机号',
        widget=forms.widgets.TextInput(
            attrs={
                'class':'layui-input',
                'placeholder':'请输入您的手机号',
                'lay-verity':'required|phone',
                'id':'username'
            }
        )
    )
    password = forms.CharField(
        max_length=20,
        label='请您输入密码',
        widget=forms.widgets.PasswordInput(
            attrs={
                'class': 'layui-input',
                'placeholder': '请您输入密码',
                'lay-verity': 'required|password',
                'id': 'password'
            }
        )
    )

    def clean_username(self):
        """
        自定义表单字段username的数据清洗函数
        """
        username = self.cleaned_data['username']
        if len(username) == 11:
            return username
        else:
            raise ValidationError('用户名为手机号')

class LoginModelForm(forms.ModelForm):
    """
    模型表单类，直接操作数据库
    """
    class Meta:
        """
        重新定义models,fields,labels,error_msg,widgets
        还有数据清洗函数
        """
        model = User
        fields = ('username', 'password')
        labels = {
            'username':'请输入您的手机号',
            'password':'请输入您的密码',
        }
        error_messages = {
            '__all__':{
                'required':'请输入内容', #必填字段错误
                'invalid':'请检查输入内容', #格式错误
            },
        }
        # 自定义表单控件属性
        widgets = {
            'username':forms.widgets.TextInput(
                attrs={
                    'class':'layui-input',
                    'placeholder':'请输入您的手机号',
                    # 'lay-verity':'required|phone',
                    'lay-verify':'required|phone',
                    'id':'username'
                }
            ),
            'password':forms.widgets.PasswordInput(
                attrs={
                    'class':'layui-input',
                    'placeholder':'请输入您的密码',
                    'lay-verify':'required|password',
                    'id':'password'
                }
            )
        }

    def clean_username(self):
        username = self.cleaned_data['username']
        if len(username) == 11:
            return username
        else:
            raise ValidationError('用户名为手机号')
